package com.shapawan.tourism.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shapawan.tourism.common.Result;
import com.shapawan.tourism.entity.SysIcon;
import com.shapawan.tourism.service.SysIconService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 系统图标控制器
 */
@Api(tags = "系统图标管理")
@RestController
@RequestMapping("/system/icon")
@CrossOrigin
@Slf4j
public class SysIconController {

    @Autowired
    private SysIconService sysIconService;

    @ApiOperation("获取图标列表")
    @GetMapping("/list")
    public Result<IPage<SysIcon>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "category", required = false) String category,
            @RequestParam(value = "status", required = false) Integer status) {
        
        log.info("获取图标列表: page={}, size={}, keyword={}, category={}, status={}", 
                page, size, keyword, category, status);
        
        // 分页参数
        Page<SysIcon> pageParam = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<SysIcon> queryWrapper = new LambdaQueryWrapper<>();
        
        // 名称或编码模糊搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like(SysIcon::getName, keyword)
                .or()
                .like(SysIcon::getCode, keyword)
                .or()
                .like(SysIcon::getDescription, keyword)
            );
        }
        
        // 按分类筛选
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq(SysIcon::getCategory, category);
        }
        
        // 按状态筛选
        if (status != null) {
            queryWrapper.eq(SysIcon::getStatus, status);
        }
        
        // 按更新时间倒序排序
        queryWrapper.orderByDesc(SysIcon::getUpdateTime);
        
        // 查询分页数据
        IPage<SysIcon> iconPage = sysIconService.page(pageParam, queryWrapper);
        
        return Result.success(iconPage);
    }

    @ApiOperation("获取所有可用图标")
    @GetMapping("/all")
    public Result<List<SysIcon>> listAll(
            @RequestParam(value = "category", required = false) String category) {
        
        // 构建查询条件
        LambdaQueryWrapper<SysIcon> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只查询启用状态的图标
        queryWrapper.eq(SysIcon::getStatus, 1);
        
        // 按分类筛选
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq(SysIcon::getCategory, category);
        }
        
        // 按更新时间倒序排序
        queryWrapper.orderByDesc(SysIcon::getUpdateTime);
        
        // 查询数据
        List<SysIcon> iconList = sysIconService.list(queryWrapper);
        
        return Result.success(iconList);
    }

    @ApiOperation("获取图标详情")
    @GetMapping("/{id}")
    public Result<SysIcon> getDetail(@PathVariable Integer id) {
        SysIcon icon = sysIconService.getById(id);
        if (icon == null) {
            return Result.failed("图标不存在");
        }
        
        return Result.success(icon);
    }

    @ApiOperation("根据编码获取图标")
    @GetMapping("/code/{code}")
    public Result<SysIcon> getByCode(@PathVariable String code) {
        SysIcon icon = sysIconService.getByCode(code);
        if (icon == null) {
            return Result.failed("图标不存在");
        }
        
        return Result.success(icon);
    }

    @ApiOperation("添加图标")
    @PostMapping("/add")
    public Result<String> add(@RequestBody @Valid IconRequest request) {
        log.info("添加图标: {}", request.getName());
        
        SysIcon icon = new SysIcon();
        icon.setName(request.getName());
        icon.setCode(request.getCode());
        icon.setCategory(request.getCategory());
        icon.setDescription(request.getDescription());
        icon.setUrl(request.getUrl());
        icon.setStatus(1); // 默认启用
        
        boolean success = sysIconService.updateWithContent(icon, request.getContent());
        
        if (success) {
            return Result.success("添加成功");
        } else {
            return Result.failed("添加失败，可能是编码已存在");
        }
    }

    @ApiOperation("更新图标")
    @PutMapping("/update")
    public Result<String> update(@RequestBody @Valid IconUpdateRequest request) {
        log.info("更新图标: id={}, name={}", request.getId(), request.getName());
        
        SysIcon icon = sysIconService.getById(request.getId());
        if (icon == null) {
            return Result.failed("图标不存在");
        }
        
        icon.setName(request.getName());
        // 图标编码不允许修改
        icon.setCategory(request.getCategory());
        icon.setDescription(request.getDescription());
        icon.setUrl(request.getUrl());
        
        boolean success = sysIconService.updateWithContent(icon, request.getContent());
        
        if (success) {
            return Result.success("更新成功");
        } else {
            return Result.failed("更新失败");
        }
    }

    @ApiOperation("更新图标状态")
    @PutMapping("/status/{id}/{status}")
    public Result<String> updateStatus(
            @PathVariable Integer id,
            @PathVariable Integer status) {
        
        log.info("更新图标状态: id={}, status={}", id, status);
        
        if (status != 0 && status != 1) {
            return Result.failed("状态值无效");
        }
        
        boolean success = sysIconService.updateStatus(id, status);
        
        if (success) {
            return Result.success("状态更新成功");
        } else {
            return Result.failed("状态更新失败");
        }
    }

    @ApiOperation("删除图标")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        log.info("删除图标: id={}", id);
        
        boolean success = sysIconService.removeById(id);
        
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.failed("删除失败");
        }
    }
    
    /**
     * 图标请求参数
     */
    @Data
    public static class IconRequest {
        @NotBlank(message = "图标名称不能为空")
        private String name;
        
        @NotBlank(message = "图标编码不能为空")
        private String code;
        
        private String category;
        
        private String description;
        
        private String url;
        
        private String content; // Base64编码的图标内容
    }
    
    /**
     * 图标更新请求参数
     */
    @Data
    public static class IconUpdateRequest {
        @NotNull(message = "图标ID不能为空")
        private Integer id;
        
        @NotBlank(message = "图标名称不能为空")
        private String name;
        
        private String category;
        
        private String description;
        
        private String url;
        
        private String content; // Base64编码的图标内容
    }
} 